package com.dhcc.myrw.config.dbconfigtwo;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.dhcc.myrw.config.dbconfig.DataSourceConfiguration;
import com.dhcc.myrw.util.SpringContextUtil;

import javax.annotation.Resource;
import javax.sql.DataSource;

@EnableTransactionManagement
@Configuration
@AutoConfigureAfter(DataSourceConfig.class)
@MapperScan(basePackages = "com.dhcc.myrw.dao")
public class MyBatisConfig {
	// XxxMapper.xml文件所在路径
	@Value("${mysql.datasource.mapperLocations}")
	private String mapperLocations;

	// 加载全局的配置文件
	@Value("${mysql.datasource.configLocation}")
	private String configLocation;
	
    @Resource(name = "myRoutingDataSource")
    private DataSource myRoutingDataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
        // 设置mapper.xml文件所在位置
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
        		.getResources(mapperLocations));
		// 设置mybatis-config.xml配置文件位置
        sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader()
        		.getResource(configLocation));
        return sqlSessionFactoryBean.getObject();
    }

    // 事务管理
    @Bean
    public PlatformTransactionManager platformTransactionManager() {
        return new DataSourceTransactionManager(myRoutingDataSource);
    }
    @Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}